import os
from os import path
from ffmpeg import probe
import shutil
from time import sleep


def sortRename(rootPwd,filetype = '.mp4'):
    #待命名队列
    qpwd = [rootPwd,]
    while(not len(qpwd)==0):
        # 获取最深一个路径
        cpwd = qpwd.pop()
        allfile = os.listdir(cpwd)
        # 先处理掉文件夹和非filetype文件
        for file in allfile:
            if  not filetype in file:
                filepath = path.join(cpwd,file)
                # 目录则进队列
                if path.isdir(filepath):
                    qpwd.append(filepath)
                    print(f'增加文件夹：{filepath}')
                # 去掉非filetype 文件
                allfile.remove(file)
        fileindex = 1
        for file in allfile:
            # 保留后缀
            newfile = file.split('.')
            # 文件名包含点时，留最后两个片段，其中包含了后缀
            if len(newfile) > 2:
                newfile = newfile[-2:]
            else:
                # 如果这个文件已经是 数字.filetype 格式，且在范围之内，则不处理
                # 如果是数字，且非0开头，且再范围内，跳过
                if newfile[0].isdigit() and newfile[0][0] != '0' and int(newfile[0]) <= len(allfile):
                    print(f'{file} 保持原名字跳过')
                    continue
            filepath = path.join(cpwd,file)
            # 改名后拼接
            while(True):
                newfile[0] = str(fileindex)
                newname = path.join(cpwd,'.'.join(newfile))
                # 如果已存在，改名后循环递增，直到找到不存在的名字
                if not os.path.exists(newname):
                    break
                else:
                    print(f'{newname} 已存在，向下寻找')
                    fileindex += 1
            os.rename(filepath,newname)
            print(f'完成拼接: {filepath} to {newname}')
            fileindex += 1

def sortPx(rootPwd):
    #待命名队列
    qpwd = [rootPwd,]
    # 只要mp4
    videotype = ['mp4']
    while(not len(qpwd)==0):
        # 获取最深一个路径
        cpwd = qpwd.pop()
        allfile = os.listdir(cpwd)
        fileindex = 1
        for file in allfile:
            # 保留后缀
            filepath = path.join(cpwd,file)
            # 目录则进队列
            if path.isdir(filepath):
                qpwd.append(filepath)
                print(f'增加文件夹：{filepath}')
            elif file.split('.')[-1].lower() in videotype:
                # 如果是视频文件
                v_with = probe(filepath)['streams'][0]['width']
                v_height = probe(filepath)['streams'][0]['height']
                if v_height > v_with:
                    dirpath = path.join(cpwd,'height')
                    if not os.path.exists(dirpath):
                        os.makedirs(dirpath)
                    shutil.move(filepath,path.join(dirpath,file))
                    print(f'移动成功：{filepath} to height')
                else:
                    dirpath = path.join(cpwd,'width')
                    if not os.path.exists(dirpath):
                        os.makedirs(dirpath)
                    shutil.move(filepath,path.join(dirpath,file))
                    print(f'移动成功：{filepath} to width')

def main():
    rootPwd = r'D:\Material\animal'
    sortRename(rootPwd)


if __name__ == '__main__':
    main()